package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.feign.schedule.IScheduleClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.TaskDto;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Slf4j
@Service
@Transactional
public class WmNewsTaskServiceImpl implements WmNewsTaskService {
    @Autowired
    private IScheduleClient scheduleClient;
    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    /**
     * 添加任务到延迟队列中
     *
     * @param id
     * @param publishTime
     */
    @Override
    @Async
    public void addNewsToTask(Integer id, Date publishTime) {
        TaskDto dto = new TaskDto();
        dto.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        dto.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        //设置执行时间
        dto.setExecuteTime(publishTime.getTime());
        //设置任务参数
        dto.setParameters(id.toString().getBytes());
        //远程feign调用延迟微服务,将文章审核任务参数数据保存到任务中
        scheduleClient.addTask(dto);
    }


    /**
     * 定时拉取消费任务,审核文章
     */
    @Scheduled(fixedRate = 1000)  //每秒钟就通过远程feign调用延迟任务服务来拉取任务
    @Override
    public void scanNewsByTask() {
        //远程调用延迟任务微服务,进行任务拉取
        ResponseResult responseResult =
                scheduleClient.popTask(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());

        if (responseResult.getCode().equals(200) && responseResult.getData() != null) {
            log.info("定时消费任务,拉取任务-进行文章审核--begin");
            TaskDto dto = JSON.parseObject(JSON.toJSONString(responseResult.getData()), TaskDto.class);
            //获取任务中的文章id
            String newsId = new String(dto.getParameters());
            //进行文章审核
            wmNewsAutoScanService.autoScanWmNews(Integer.valueOf(newsId));
            log.info("定时消费任务,拉取任务-进行文章审核--end");
        }
    }
}
